<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" type="success" @click="handleSubmit"> 提交添加 </el-button>
    </div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>基本信息</span>
      </div>
      <el-form :model="user">
        <el-form-item label="用户名" :label-width="formLabelWidth">
          <el-input v-model="user.username" autocomplete="off" />
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth">
          <el-input v-model="user.password" autocomplete="off" />
        </el-form-item>
        <el-form-item label="角色" :label-width="formLabelWidth">
          <el-tag
            v-for="tag in dynamicTags"
            :key="tag"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)"
          >
            {{ tag }}
          </el-tag>
          <el-input
            v-if="inputVisible"
            ref="saveTagInput"
            v-model="inputValue"
            class="input-new-tag"
            size="small"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          />
          <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
        </el-form-item>
      </el-form>
    </el-card>

  </div>
</template>

<script>
import { register } from '@/api/user'

export default {
  name: 'RG602',
  components: { },
  data() {
    return {
      formLabelWidth: '200px',
      dynamicTags: ['admin', 'editor'],
      inputVisible: false,
      inputValue: '',
      user: {
        username: '',
        password: '',
        roles: []
      }
    }
  },
  created() {
  },
  methods: {
    handleSubmit() {
      this.user.roles = this.dynamicTags
      register(this.user).then(response => {
        if (response.code === 200) {
          this.$message({
            type: 'success',
            message: response.message
          })
          this.$router.push({ path: '/user/index' })
        } else this.$message(response.message)
      })
    },
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
    },

    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        this.dynamicTags.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    }
  }
}
</script>

<style scoped>
.box-card{
    margin-bottom: 20px;
}
.el-tag + .el-tag {
    margin-left: 10px;
}
.button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
}
.input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
}

</style>
